package com.atguigu.ggkt.order.config;

import com.atguigu.ggkt.utils.Base64FileConversion;
import com.atguigu.ggkt.utils.LogTool;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.IOException;

@Configuration
@MapperScan("com.atguigu.ggkt.order.mapper")
public class OrderConfig {

    @Value("${wechat.mch.id-1}")
    private String mchId1;
    @Value("${wechat.mch.id-1-privateKeyPath}")
    private String privateKeyPath;
    @Value("${wechat.mch.id-1-merchantSerialNumber}")
    private String merchantSerialNumber;
    @Value("${wechat.mch.id-1-apiV3Key}")
    private String apiV3Key;
    @Value("${wechat.mch.id-1-sign-pem}")
    private String signPem;

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @Bean
    public RSAAutoCertificateConfig rSAAutoCertificateConfig() throws IOException {

        File file = new File(privateKeyPath);
        if (!file.exists()) {
            // 把base64字符串转成文件
            LogTool.info(this.getClass(), "go to create private key file!");
            Base64FileConversion.decodeBase64ToFile(signPem, file);
        }
        // 使用自动更新平台证书的RSA配置
        RSAAutoCertificateConfig config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(mchId1)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
        return config;
    }
}
